package com.cxyzy.camera2demo;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.TextureView;
import android.widget.ImageView;

import com.blankj.utilcode.util.ToastUtils;
import com.cxyzy.camera2library.CameraHelper;

import static com.cxyzy.camera2demo.Constants.PHOTO_INTERVAL;

/**
 * 利用Camera2实现点击拍照
 */
public class CameraActivity extends AppCompatActivity {

    private ImageView ivTakePhoto;//拍照&录像按钮
    private ImageView ivSwitchCamera;//切换前后摄像头
    private ImageView ivLightOn;//开关闪光灯
    private ImageView ivClose;//关闭该Activity
    private CameraHelper cameraHelper;
    private TextureView mTextureView;
    private int photoInterval = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera);
        processIntent();
        initViews();
        cameraHelper = new CameraHelper(this, mTextureView, this::showPhoto);
        iniListeners();
    }

    private void processIntent() {
        Intent intent = getIntent();
        if (intent != null) {
            photoInterval = intent.getIntExtra(PHOTO_INTERVAL, 0);
        }
    }

    private void showPhoto(String imageFilePath) {
//        Intent intent = new Intent(CameraActivity.this, ShowImageActivity.class);
//        intent.putExtra(INTENT_PATH_SAVE_PIC, imageFilePath);
//        startActivity(intent);
        ToastUtils.showShort("path:" + imageFilePath);
    }

    protected void initViews() {
        mTextureView = findViewById(R.id.textureView);
        ivTakePhoto = findViewById(R.id.iv_takePhoto);
        ivSwitchCamera = findViewById(R.id.iv_switchCamera);
        ivLightOn = findViewById(R.id.iv_lightOn);
        ivClose = findViewById(R.id.iv_close);
    }


    protected void iniListeners() {
        ivSwitchCamera.setOnClickListener(v -> cameraHelper.switchCamera());
        ivLightOn.setOnClickListener(v -> switchFlashlight());
        ivClose.setOnClickListener(v -> finish());
        ivTakePhoto.setOnClickListener(v -> cameraHelper.capture(photoInterval));
    }

    /**
     * ***************************************打开和关闭闪光灯****************************************
     */
    private void switchFlashlight() {
        ivLightOn.setSelected(cameraHelper.switchFlashlight());
    }

    /**
     * ******************************Activity生命周期*****************************************
     */
    @Override
    protected void onResume() {
        super.onResume();
        ivLightOn.setSelected(false);
        cameraHelper.setFlashlight(false);
        cameraHelper.switchCamera(false);
        cameraHelper.zoomNormal();
    }

    @Override
    protected void onPause() {
        cameraHelper.onFinishCapture();//释放资源
        super.onPause();
    }

}
